<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="12">
        <!-- 我的信息 -->
        <el-card shadow="hover" class="mb_m">
          <template #header>
            <div class="clearfix">
              <span>我的信息</span>
            </div>
          </template>
          <div class="info">
            <div class="info-image" @click="showDialog">
              <UserAvatar :src="userInfo.avatarUrl" :size="100" />
              <span class="info-edit">
                <i class="el-icon-lx-camerafill"></i>
              </span>
            </div>
            <div class="info-name">{{ userInfo.nickname }}</div>
            <div v-if="userInfo.description" class="info-desc">
              {{ userInfo.description }}
            </div>
            <div v-else class="info-desc color_gray">
              您还没有添加简介，来秀出你的个性吧！
            </div>
          </div>
        </el-card>

        <!-- 机构信息 -->
        <el-card shadow="hover">
          <template #header>
            <div class="clearfix d_f j_s a_c">
              <span>机构信息</span>
              <el-button-group v-if="orgDetail.orgManagerId === userInfo.id">
                <el-button
                  size="mini"
                  type="primary"
                  :disabled="orgLoading"
                  @click="handleEditOrg"
                >
                  编辑
                </el-button>
                <el-button
                  type="warning"
                  size="mini"
                  plain
                  :disabled="orgLoading"
                  @click="outOfOrg"
                >
                  退出
                </el-button>
              </el-button-group>
              <el-button
                v-else
                type="warning"
                size="mini"
                plain
                :disabled="orgLoading"
                @click="outOfOrg"
              >
                退出
              </el-button>
            </div>
          </template>
          <div class="org_info" v-loading="orgLoading">
            <div class="org_name">
              <span>{{ orgDetail.orgName }}</span>
            </div>
            <div class="mb_s d_f a_c j_s">
              <div>
                <!-- 机构状态 -->
                <el-tag
                  v-if="orgDetail.orgStatus !== '1'"
                  type="danger"
                  size="small"
                >
                  已被停用
                </el-tag>
                <el-tag
                  v-else-if="orgDetail.canJoin === '1'"
                  type="success"
                  size="small"
                >
                  可加入
                </el-tag>
                <el-tag
                  v-else-if="orgDetail.canJoin === '0'"
                  type="info"
                  size="small"
                >
                  不可加入
                </el-tag>
                <!-- 机构是否开启验证 -->
                <el-tag
                  v-if="orgDetail.isOpenVerification !== '1'"
                  type="success"
                  size="small"
                >
                  无需验证
                </el-tag>
                <el-tag v-else type="warning" size="small"> 需要验证 </el-tag>
              </div>
              <span>{{ orgDetail.memberCount }}人</span>
            </div>
            <div class="d_f j_s">
              <div>
                <span>管理人：</span>
                <span>{{ orgDetail.orgManagerName }}</span>
              </div>
              <div>
                <span>创建时间：</span>
                <span>
                  {{
                    orgDetail.createdTime
                      ? orgDetail.createdTime.slice(0, 10)
                      : ""
                  }}
                </span>
              </div>
            </div>
            <div>
              <span>机构简介：</span>
              <span v-if="orgDetail.orgDesc">{{ orgDetail.orgDesc }}</span>
              <span v-else class="color_gray">暂无</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <!-- 个人信息 -->
        <el-card shadow="hover" class="mb_m">
          <template #header>
            <div class="clearfix d_f j_s a_c">
              <span>{{ isEdit ? "编辑" : "查看" }}资料</span>
              <el-button-group>
                <el-button
                  v-if="isEdit"
                  size="mini"
                  :loading="editBtnLoading"
                  type="primary"
                  @click="onSubmit"
                >
                  保存
                </el-button>
                <el-button size="mini" @click="toggleEditStatus">
                  {{ isEdit ? "取消" : "编辑" }}
                </el-button>
              </el-button-group>
            </div>
          </template>
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="90px"
          >
            <el-form-item label="登录名：">
              {{ userInfo.username }}
            </el-form-item>

            <el-form-item label="角色：">
              {{ userInfo.roleName }}
            </el-form-item>

            <el-form-item label="昵称：" prop="nickname">
              <el-input v-if="isEdit" v-model="form.nickname"></el-input>
              <span v-else :class="{ color_gray: !form.nickname }">
                {{ form.nickname || "未填写" }}
              </span>
            </el-form-item>

            <el-form-item
              label="姓名："
              prop="truename"
              :class="{
                bg_yellow: bgYellowControl.truename,
              }"
            >
              <el-input v-if="isEdit" v-model="form.truename"></el-input>
              <span v-else :class="{ color_gray: !form.truename }">
                {{ form.truename || "未填写" }}
              </span>
            </el-form-item>

            <el-form-item label="性别：" prop="gender">
              <el-select
                v-if="isEdit"
                v-model="form.gender"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in genderSelectList"
                  :key="item.val"
                  :label="item.label"
                  :value="item.val"
                >
                </el-option>
              </el-select>
              <span v-else :class="{ color_gray: !form.gender }">
                {{ $filters.sexFilter(form.gender) }}
              </span>
            </el-form-item>

            <el-form-item label="邮箱：" prop="email">
              <el-input v-if="isEdit" v-model="form.email"></el-input>
              <span v-else :class="{ color_gray: !form.email }">
                {{ form.email || "未填写" }}
              </span>
            </el-form-item>

            <el-form-item label="手机号：" prop="phone">
              <el-input v-if="isEdit" v-model="form.phone"></el-input>
              <span v-else :class="{ color_gray: !form.phone }">
                {{ form.phone || "未填写" }}
              </span>
            </el-form-item>

            <el-form-item label="个人简介：" prop="description">
              <el-input
                v-if="isEdit"
                type="textarea"
                rows="4"
                v-model="form.description"
              ></el-input>
              <span v-else :class="{ color_gray: !form.description }">
                {{ form.description || "未填写" }}
              </span>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 配置 -->
        <el-card shadow="hover">
          <template #header>
            <div class="clearfix d_f j_s a_c">
              <span>配置</span>
              <el-button-group>
                <el-button
                  v-if="isEditConfig"
                  size="mini"
                  :loading="saveConfigBtnLoading"
                  type="primary"
                  @click="saveConfigMethod"
                >
                  保存
                </el-button>
                <el-button size="mini" @click="toggleEditConfigStatus">
                  {{ isEditConfig ? "取消" : "修改" }}
                </el-button>
              </el-button-group>
            </div>
          </template>
          <el-form
            ref="configFormRef"
            :model="configFormData"
            :rules="configFormRules"
            label-width="170px"
            v-loading="configFormLoading"
          >
            <el-form-item label="是否开启邮箱提醒：" prop="isOpenEmailNotation">
              <el-switch
                v-model="configFormData.isOpenEmailNotation"
                inline-prompt
                active-text="开启"
                inactive-text="关闭"
                :disabled="!isEditConfig"
              />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图片选择裁剪弹框 -->
    <CropperImageDialog ref="cropperImageDialogRef" @croped="onImageSaved" />

    <!-- 机构修改弹框 -->
    <OrgFormDialog
      ref="orgFormDialogRef"
      :managerVisibel="false"
      :canJoinVisibel="true"
      :prepareData="orgPrepareData"
      @updateSuccess="getOrgDetail"
    />
  </div>
</template>

<script>
import {
  reactive,
  ref,
  computed,
  watch,
  getCurrentInstance,
  onActivated,
  nextTick,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";
import CropperImageDialog from "../../components/CropperImageDialog.vue";
import UserAvatar from "../../components/UserAvatar.vue";
import OrgFormDialog from "../organization/components/OrgFormDialog.vue";

const initFormData = () => {
  return {
    nickname: null,
    truename: null,
    description: null,
    avatar: null,
    phone: null,
    email: null,
    gender: null,
    departmentId: null,
    groupId: null,
  };
};

const initConfigFormData = () => {
  return {
    // 是否开启邮箱提醒
    isOpenEmailNotation: true,
  };
};

export default {
  name: "user",
  components: {
    CropperImageDialog,
    UserAvatar,
    OrgFormDialog,
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const $route = useRoute();
    const $router = useRouter();
    // debugger
    const store = useStore();
    const formRef = ref(null);
    const form = reactive(initFormData());
    // 表单校验规则
    const rules = reactive({
      nickname: [
        {
          required: true,
          trigger: "blur",
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error("请输入你的昵称"));
            } else {
              callback();
            }
          },
        },
      ],
    });
    const genderSelectList = reactive([
      { label: "男", val: "1" },
      { label: "女", val: "0" },
    ]);

    const cropperImageDialogRef = ref(null);

    const userInfo = computed(() => store.state.user.userInfo);

    // watch()可以直接观察一个包装对象：
    watch(
      () => userInfo,
      (val) => {
        // console.log('watch => userInfo', val.value)
        Object.keys(form).forEach((key) => {
          form[key] = val.value[key];
        });
      },
      { deep: true, immediate: true }
    );

    // ---------------------  机构相关 start  -----------------------------

    const orgLoading = ref(false);
    const orgFormDialogRef = ref(null);
    const orgPrepareData = reactive({
      orgStatusSelectList: [],
      canJoinSelectList: [],
      isOpenVerificationSelectList: [],
    });

    // 机构信息
    const orgDetail = reactive({
      id: null,
      orgName: null,
      orgShortName: null,
      orgStatus: null,
      orgDesc: null,
      orgAvatar: null,
      orgManagerId: null,
      canJoin: null,
      orgStatusLabel: null,
      canJoinLabel: null,
      orgManagerName: null,
      createdTime: null,
      memberCount: null,
      isOpenVerification: null,
      verifyQuestion: null,
      verifyAnswer: null,
    });

    // 查询预加载数据
    const getOrgPreparedData = () => {
      $api.organization
        .preparedData()
        .then((res) => {
          Object.keys(orgPrepareData).forEach((key) => {
            orgPrepareData[key] = res.data[key] || [];
          });
        })
        .catch((err) => {
          console.error("getOrgPreparedData error: ", err);
        })
        .finally(() => {});
    };

    // 获取机构详情
    const getOrgDetail = (cropImg) => {
      if (!userInfo.value.orgId) {
        return;
      }
      orgLoading.value = true;
      $api.organization
        .getById({
          id: userInfo.value.orgId,
        })
        .then((res) => {
          Object.keys(orgDetail).forEach((key) => {
            orgDetail[key] = res.data[key];
          });
        })
        .catch((err) => {
          console.error("getOrgDetail error: ", err);
        })
        .finally(() => {
          orgLoading.value = false;
        });
    };

    // 修改机构
    const handleEditOrg = () => {
      orgFormDialogRef.value && orgFormDialogRef.value.open(orgDetail);
    };

    // 退出机构
    const outOfOrg = () => {
      let text = "";
      // 如果当前用户是机构管理员
      if (orgDetail.memberCount === 1) {
        text = `当前机构不足2人，退出后该机构将被删除，请确认是否继续？`;
      } else if (orgDetail.orgManagerId === userInfo.value.id) {
        text = `您是【${orgDetail.orgName}】的机构管理员，退出后管理员权限将自动移交给其他人，请确认是否继续？`;
      } else {
        text = `确定要退出【${orgDetail.orgName}】机构吗？`;
      }
      ElMessageBox.confirm(text, "提示", { type: "warning" })
        .then(() => {
          userUnboundOrg();
        })
        .catch(() => {});
    };

    // 当前登录用户解除关联的机构
    const userUnboundOrg = () => {
      if (!userInfo.value.orgId) {
        return;
      }
      $api.users
        .userUnboundOrg({
          orgId: userInfo.value.orgId,
        })
        .then((res) => {
          ElMessage.success("解除关联成功");
          $router.push("/ChooseOrg");
          // 刷新用户信息
          store.dispatch("user/getUserInfo");
        })
        .catch((err) => {
          console.error("userUnboundOrg error: ", err);
        });
    };

    // ----------------  机构相关 end  ---------------------------------

    // ----------------  用户头像相关 start ----------------------------
    const showDialog = () => {
      nextTick(() => {
        cropperImageDialogRef.value.open(
          userInfo.value.avatarUrl || store.state.defaultAvatar
        );
      });
    };

    const onImageSaved = (cropImg) => {
      // console.log("cropImg ==>", cropImg);
      cropperImageDialogRef.value.confirmBtnLoading = true;
      $api.users
        .updateAvatar({
          avatarBase64Str: cropImg,
        })
        .then((res) => {
          ElMessage.success("操作成功！");
          store.commit("user/setUserInfo", res.data);
          cropperImageDialogRef.value.confirmBtnLoading = false;
          cropperImageDialogRef.value.close();
        })
        .catch((err) => {
          cropperImageDialogRef.value.confirmBtnLoading = false;
          console.error("uploadImage error: ", err);
        });
    };
    // ------------------------- 用户头像相关 end ----------------------

    // 控制是否编辑资料
    const isEdit = ref(false);
    const editBtnLoading = ref(false);

    const toggleEditStatus = () => {
      if (editBtnLoading.value) {
        return;
      }
      // 当点击取消的时候，清空表单校验，还原被修改的数据
      if (isEdit.value) {
        formRef.value.resetFields();
      }
      isEdit.value = !isEdit.value;
    };

    // 提交修改用户信息
    const onSubmit = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          editBtnLoading.value = true;
          $api.users
            .usersUpdate(form)
            .then((res) => {
              editBtnLoading.value = false;
              isEdit.value = false;
              ElMessage.success("修改成功！");
              // 刷新用户信息
              store.dispatch("user/getUserInfo");
            })
            .catch((err) => {
              editBtnLoading.value = false;
              console.error("usersUpdate error: ", err);
            });
        }
      });
    };

    const bgYellowControl = reactive({
      nickname: false,
      truename: false,
      description: false,
      avatar: false,
      phone: false,
      email: false,
      gender: false,
      departmentId: false,
      groupId: false,
    });

    // ------------------------------ 配置相关 start ------------------------------
    const saveConfigBtnLoading = ref(false);
    const configFormLoading = ref(false);
    const isEditConfig = ref(false);
    const configFormRef = ref(null);
    const configFormData = reactive(initConfigFormData());

    // 表单校验规则
    const configFormRules = reactive({
      nickname: [
        {
          required: true,
          trigger: "blur",
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error("请输入你的昵称"));
            } else {
              callback();
            }
          },
        },
      ],
    });

    // 获取用户配置信息
    const getUserConfig = () => {
      configFormLoading.value = true;
      $api.users
        .getUserConfig({})
        .then((res) => {
          Object.keys(configFormData).forEach((key) => {
            configFormData[key] = res.data[key];
          });
        })
        .catch((err) => {
          console.error("getUserConfig error: ", err);
        })
        .finally(() => {
          configFormLoading.value = false;
        });
    };

    // 提交修改用户信息
    const saveConfigMethod = () => {
      configFormRef.value.validate((valid) => {
        if (valid) {
          saveConfigBtnLoading.value = true;
          $api.users
            .setUserConfig(configFormData)
            .then((res) => {
              saveConfigBtnLoading.value = false;
              isEditConfig.value = false;
              ElMessage.success("修改成功！");
            })
            .catch((err) => {
              saveConfigBtnLoading.value = false;
              console.error("saveConfigMethod error: ", err);
            });
        }
      });
    };

    const toggleEditConfigStatus = () => {
      if (saveConfigBtnLoading.value) {
        return;
      }
      // 当点击取消的时候，清空表单校验，还原被修改的数据
      if (isEditConfig.value) {
        getUserConfig();
      }
      isEditConfig.value = !isEditConfig.value;
    };

    // ------------------------------ 配置相关 end ------------------------------

    /**
     * 初始化
     */
    getOrgDetail();
    getOrgPreparedData();
    getUserConfig();

    onActivated(() => {
      Object.keys(bgYellowControl).forEach((key) => {
        bgYellowControl[key] = false;
      });
      if ($route.params) {
        Object.keys($route.params).forEach((key) => {
          if (
            $route.params &&
            Object.prototype.hasOwnProperty.call(bgYellowControl, key)
          ) {
            bgYellowControl[key] = true;
          }
        });
      }
    });

    return {
      form,
      rules,
      formRef,
      showDialog,
      userInfo,
      isEdit,
      editBtnLoading,
      toggleEditStatus,
      onSubmit,
      genderSelectList,
      bgYellowControl,
      cropperImageDialogRef,
      onImageSaved,
      outOfOrg,
      orgDetail,
      orgLoading,
      getOrgDetail,
      orgFormDialogRef,
      handleEditOrg,
      orgPrepareData,
      saveConfigBtnLoading,
      configFormData,
      saveConfigMethod,
      toggleEditConfigStatus,
      configFormRules,
      isEditConfig,
      configFormRef,
      configFormLoading,
    };
  },
};
</script>

<style lang="less" scoped>
.info {
  text-align: center;
  padding: 35px 0;
}
.info-image {
  position: relative;
  margin: auto;
  width: 100px;
  height: 100px;
  background: #f8f8f8;
  /* border: 1px solid #eee; */
  border-radius: 50px;
  overflow: hidden;
}
.info-image img {
  width: 100%;
  height: 100%;
}
.info-edit {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s ease;
}
.info-edit i {
  color: #eee;
  font-size: 25px;
}
.info-image:hover .info-edit {
  opacity: 1;
}
.info-name {
  margin: 15px 0 10px;
  font-size: 24px;
  font-weight: 500;
  color: #262626;
}
.crop-demo-btn {
  position: relative;
}
.crop-input {
  position: absolute;
  width: 100px;
  height: 40px;
  left: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}
.button {
  padding: 0;
  min-height: auto;
}
.clearfix {
  line-height: 28px;
}
.bg_yellow {
  border-radius: 4px;
  background-color: rgba(222, 184, 135, 0);
  animation: show_bg 5s linear both;
}

.org_info {
  line-height: 24px;
  .org_name {
    font-size: 24px;
    font-weight: 500;
    color: #262626;
    margin-bottom: 10px;
  }
  :deep(.el-tag + .el-tag) {
    margin-left: 10px;
  }
}

@keyframes show_bg {
  0% {
    background-color: rgba(222, 184, 135, 0);
  }
  16% {
    background-color: rgba(222, 184, 135, 1);
  }
  33% {
    background-color: rgba(222, 184, 135, 0);
  }
  49% {
    background-color: rgba(222, 184, 135, 1);
  }
  65% {
    background-color: rgba(222, 184, 135, 0);
  }
  82% {
    background-color: rgba(222, 184, 135, 1);
  }
  100% {
    background-color: rgba(222, 184, 135, 0);
  }
}
</style>
